import React from 'react';
import { NavLink, match } from 'react-router-dom';
import { Location } from 'history';

import { IMenuProps } from './Menu';

interface IMenuItemProps {
  to?: string;
  menu?: React.ReactElement<IMenuProps>;
  open?: boolean;
}

interface IMenuItemState {
  open: boolean;
}

export default class MenuItem extends React.Component<IMenuItemProps, IMenuItemState> {
  constructor(props: IMenuItemProps) {
    super(props);
    this.state = { open: !!this.props.open };
    this.onClick = this.onClick.bind(this);
    this.renderWrapper = this.renderWrapper.bind(this);
    this.isActive = this.isActive.bind(this);
  }

  public onClick(event: React.MouseEvent) {
    event.stopPropagation();
    if (this.props.menu) {
      this.setState({
        open: !this.state.open,
      });
    }
  }

  public isActive(match: match<any>, location: Location) {
    return match && match.url === location.pathname;
  }

  public renderWrapper() {
    if (this.props.to) {
      return <NavLink
        strict
        isActive={this.isActive}
        activeClassName="active"
        to={this.props.to}
      >
        {this.props.children}
      </NavLink>;
    }
    return <span>{this.props.children}</span>;
  }

  public render() {
    const iconDirection = this.state.open ? 'down' : 'right';
    // 有子菜单时显示图标
    const subMenu = this.props.menu;
    return (
      <li className="menu-item" onClick={this.onClick}>
        {this.renderWrapper()}
        {subMenu ? <i className={`pull-right icon icon-${iconDirection} text text-sm`} /> : null}
        {this.state.open && subMenu}
      </li>
    );
  }
}
